<template>
  <div class="chat-container">
      <div v-for="(message, index) in messages" :key="index" :class="{ 'right-message': message.senderName === '我', 'left-message': message.senderName !== '我' }">
        <a-comment>

          <template #author>
            <span v-if="message.senderName === '我'" class="author-right">{{ message.senderName }}</span>
            <span v-else>{{ message.senderName }}</span>
          </template>
          <template #content>
            <p   class="typing-effect" ref="typingEffect">{{ message.message }}</p>
          </template>
          <template #avatar>
            <a-avatar :src="message.senderAvatar" />
          </template>
        </a-comment>
      </div>
    <div class="send-message">
      <a-input v-model:value="newMessage" placeholder="输入消息"  @keydown.enter="sendMessage"/>
      <a-button type="primary" @click="sendMessage">发送</a-button>
    </div>
  </div>
</template>

<script>

export default {
  data() {
    return {
      messages: [
        {
          senderName: 'Alice',
          senderAvatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
          message: '你好！ \n 11111'
        },
        {
          senderName: 'Bob',
          senderAvatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
          message: '嗨，最近怎么样？'
        }
      ],
      newMessage: ''
    };
  },
  mounted() {
    this.startTyping();
  },
  methods: {
    sendMessage() {
      if (this.newMessage.trim()) {
        this.messages.push({
          senderName: '我',
          senderAvatar: 'https://static.jeecg.com/temp/国炬软件logo_1606575029126.png',
          message: this.newMessage
        });
        this.newMessage = ''; // 清空输入框
      }
    },
    startTyping() {
      if (this.currentIndex < this.text.length) {
        this.$refs.typingEffect.textContent += this.text[this.currentIndex];
        this.currentIndex++;
        setTimeout(() => this.startTyping(), 100); // 每个字符之间的延迟时间（毫秒）
      }
    },
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
}

.send-message {
  display: flex;
  align-items: center;
  padding: 16px;
  border-top: 1px solid #e8e8e8;
}

/* 使作者名字靠右 */
.author-right {
  margin-right: 0;
  margin-left: 16px;
}

/* 使“我”的消息靠右 */
.right-message {
  text-align: left;
   border-radius: 20px;
  margin-bottom: 10px;
}

/* 使“我”的消息头像靠右 */
.right-avatar {
  float: right;
}

/* 使其他消息靠左 */
.left-message {
  text-align: left;
  background-color: white;
  border-radius: 20px;
  margin-bottom: 10px;
}

/* 使其他消息头像靠左 */
.left-avatar {
  float: left;
}

</style>

